<script setup>

import { ref, reactive, toRefs, onMounted, computed } from 'vue'
import api from '@/api'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/store/modules/user'

const router = useRouter()

const user = useUserStore()
user.loadList()

const nameData = ref([])
const paramData = ref([])
const param = ref([])

const data = reactive({
    drawer: false,
    formSearch: {

        pym: ''
    },
    originData: [],
    tableData: [],
    formData: {
        id: '',
        cId: '',
        cName: '',
        category: '',
        name: '',

        unit: '',
        pIds: [],
    }
})

const onSubmit = () => {

    if(tableRef.value) {
        data.formData.id = ''
        tableRef.value.setCurrentRow()
    }

    return new Promise((resolve, reject) => {
        api.post('api/comp/emNamelList', {
            pym: data.formSearch.pym
        }).then(res => {

            data.originData = res.d
            for(let d of data.originData) {
                d.param = d.nameParamDTOList.map(i => i.pName).join(',')
            }
            fillTable(page.value)
            resolve()

        }).catch(error => {
            data.value = []
            fillTable(page.value)
        })
    })

}


const querySearch = (str, cb) => {
    api.post('api/comp/classList', {'pym': str})
    .then(res => {
        nameData.value = res.d

        cb(res.d.map(i => ({'value': i.name, 'id': i.id})))
    })
}

const handleSelect = i => {
    formData.cId = i.id
}




const submit = state => {

    switch (Number.parseInt(state)) {
        case 0:
            api.post('api/comp/emNameEdit', data.formData)
                .then(res => {
                    if (res.c === 0) {

                        api.post('api/comp/emNamelList')
                        .then(res => {
                            let id = res.d.find(i => i.name === data.formData.name).id
                            handleParam()
                            api.post('api/comp/nameParamEdit', {'nId': id, 'pIds': formData.pIds.join(',')})
                            .then(res => {
                                ElMessage({
                                    message: '添加成功',
                                    type: ''
                                })
                            })
                        })


                    } else {
                        ElMessage({
                            message: res.m,
                            type: 'error'
                        })
                    }
                })
            break
        case 1:
            api.post('api/comp/emNameEdit', data.formData)
                .then(res => {
                    if (res.c === 0) {
                        handleParam()
                        api.post('api/comp/nameParamEdit', {'nId': formData.id, 'pIds': formData.pIds.join(',')})
                        .then(res => {
                            ElMessage({
                                message: '添加成功',
                                type: ''
                            })
                        })
                        ElMessage({
                            message: '修改成功',
                            type: ''
                        })
                    } else {
                        ElMessage({
                            message: res.m,
                            type: 'error'
                        })
                    }
                })
            break
        case 2:
            api.post('api/comp/emNameDel', data.formData)
                .then(res => {
                    if (res.c === 0) {
                        ElMessage({
                            message: '删除成功',
                            type: ''
                        })
                    } else {
                        ElMessage({
                            message: res.m,
                            type: 'error'
                        })
                    }
                })
            break
        default:
            break
    }
}

api.post('api/comp/paramList', {'pym': ''})
.then(res => {
    paramData.value = res.d
})

const handleParam = () => {
    data.formData.pIds = []
    for(let p of param.value) {
        if(!p) continue
        data.formData.pIds.push(paramData.value.find(i => i.name === p).id)
    }
}

const numberPerPage = 10

const disabledPre = computed(() => (page.value === 1))
const disabledNext = computed(() => (page.value * numberPerPage >= data.originData.length))

const
    page = ref(1)

const nextPage = () => {
    page.value ++

    fillTable(page.value)
}

const prePage = () => {
    page.value --

    fillTable(page.value)
}

// 这里要用深拷贝 否则 data和tableData 会同时改变
const fillTable = num => {
    data.tableData = JSON.parse(JSON.stringify([].slice.call(data.originData, (num - 1) * numberPerPage, num * numberPerPage)))
    // for(let d of data.tableData) {
    //     if(d.code.length > 7) {
    //         d.code = d.code.slice(0, 7) + '...'
    //     }
    //     if(d.supplier.length > 7) {
    //         d.supplier = d.supplier.slice(0, 7) + '...'
    //     }
    // }
}


const currentRow = ref()
const tableRef = ref()

const setCurrent = row => {
    tableRef.value.setCurrentRow(row)
}

const handleCurrentChange = row => {
    if(row) {
        data.formData = row
        param.value = row.param.split(',')
        handleParam()
    } else {
        data.formData = {
            id: '',
            cId: '',
            cName: '',
            category: '',
            name: '',

            unit: '',
            pIds: [],
        }
    }
}

const onDblClick = () => {
    router.push('/class')
}

onSubmit()

const { formSearch, originData, tableData, formData, drawer } = toRefs(data)

</script>

<template>
    <div emName="content">
        <page-main>
            <div id="form">
                <div>
                    <el-form :inline="true" :model="formSearch" em-name="demo-form-inline" size="mini">
                        <el-form-item label="设备名称">
                            <el-input  v-model="formSearch.pym" placeholder="输入设备名称拼音码" />
                        </el-form-item>

                        <el-form-item>
                            <el-button type="primary" @click="onSubmit">查询</el-button>
                        </el-form-item>
                    </el-form>
                </div>

                <el-table
                    ref="tableRef"
                    :data="tableData" :cell-style="rowemName"
                    style="width: 900px;height:350px;font-size: 10px;"
                    highlight-current-row
                    @current-change="handleCurrentChange"
                >
                    <el-table-column
                        fixed
                        prop="cName"
                        label="设备分类"
                        width="80px"
                    />
                    <el-table-column
                        fixed
                        prop="name"
                        label="设备名称"
                        width="120px"
                    />
                    <el-table-column
                        fixed
                        prop="category"
                        label="设备类别"
                        width="120px"
                    />
                    <el-table-column
                        fixed
                        prop="unit"
                        label="设备单位"
                        width="120px"
                    />
                    <el-table-column
                        fixed
                        prop="lifeSpan"
                        label="使用年限"
                        width="120px"
                    />
                    <el-table-column
                        fixed
                        prop="param"
                        label="参数名"
                        width="320px"
                    />
                </el-table>
                <div :style="{height: '100px', width: '100%', position: 'relative'}">
                    <div style="height: 30px;
                    width: 240px;
                    position: absolute;
                    top: 0;
                    left: 0;
                    right: 0;
                    bottom: 0;
                    margin: auto;

                    font-size: 8px;">
                        <span>第&nbsp;{{page}}&nbsp;页</span>
                        <span>共&nbsp;{{ Math.ceil(originData.length / numberPerPage) }}&nbsp;页   </span>


                        <el-button-group>
                            <el-button type="primary" @click="prePage" :disabled="disabledPre">上页</el-button>
                            <el-button type="primary" @click="nextPage" :disabled="disabledNext">下页</el-button>
                        </el-button-group>
                    </div>
                </div>

                <!-- <el-button type="primary" style="margin-top: 20px;" @click="drawer = true">设备名称操作</el-button> -->

                <!-- <el-drawer
                    v-model="drawer"
                    title="操作"
                    direction="rtl"
                    custom-em-name="demo-drawer"
                    size="30%"
                > -->
                <el-card style="margin-top: 40px;">
                    <el-form>


                            <el-form-item label="设备名称">
                                <el-input  v-model="formData.name" />
                            </el-form-item>
                            <el-form-item label="设备单位">
                                <el-select v-model="formData.unit" >
                                    <el-option label="台" value="台" />
                                    <el-option label="个" value="个" />
                                    <el-option label="挂" value="挂" />
                                    <el-option label="辆" value="辆" />
                                </el-select>
                            </el-form-item>

                            <el-form-item label="设备分类" @dblclick.native="onDblClick">
                                <el-autocomplete
                                    v-model="formData.cName"
                                    :fetch-suggestions="querySearch"
                                    placeholder="请输入设备分类"
                                    @select="handleSelect"
                                />
                            </el-form-item>

                            <el-form-item label="设备类别">
                                <el-select v-model="formData.category">
                                    <el-option label="机电设备" value="机电设备"/>
                                    <el-option label="五小" value="五小"/>
                                    <el-option label="其他" value="其他"/>
                                </el-select>
                            </el-form-item>

                            <el-form-item label="全部参数">
                                <el-checkbox-group v-model="param">
                                        <el-checkbox v-for="i in paramData" :key="i" :label="i.name" />
                                  </el-checkbox-group>

                            </el-form-item>



                        <el-form-item>
                            <el-button type="primary" :loading="loading" @click="submit(0)" :disabled="!(formData.id === '')">添&nbsp;&nbsp;&nbsp;&nbsp;加</el-button>
                            <el-button type="primary" :loading="loading" @click="submit(1)" :disabled="(formData.id === '')">修&nbsp;&nbsp;&nbsp;&nbsp;改</el-button>
                            <el-button type="primary" :loading="loading" @click="submit(2)" :disabled="(formData.id === '')">删&nbsp;&nbsp;&nbsp;&nbsp;除</el-button>
                        </el-form-item>
                    </el-form>
                <!-- </el-drawer> -->
                </el-card>
            </div>
        </page-main>
    </div>
</template>

<style>

</style>
